import axios from 'axios'
import { Notification } from 'element-ui'
import Cookies from 'js-cookie'


class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        token: `${Cookies.get('JSESSIONID')}`
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  //重新登录
  reLogin () {
    window.location.href = 'http://ssocs.quanyou.com.cn/login?service=http://emcs.quanyou.com.cn/shopactivity/shiro-cas'
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
		console.log('2222222222222222')
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      // session失效重新登录
      if (res.data && res.data.code === 311) {
        // Cookies.remove('JSESSIONID')
        this.reLogin()
        return {}
      }
      const { data, status } = res
	  console.log('rrrrrrrrrrrrrrrrrrr:' + this.theOptions.url)
      return { data, status }
    }, error => {
		console.log('eeeeeeeeeeeeee:' + this.theOptions.url)
		this.theOptions.ttt = 2;
		return this.request(this.theOptions);
		console.log(url)
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      // 全局错误通知
      if (error.response.status >= 400) {
        Notification.error({
          message: !errorInfo.data.message ? error.message : errorInfo.data.message
        })
      }
      // addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }
  
  request (options) {
	options.timeout = 60000;
	
	this.theOptions = options;

	if (this.theOptions.url != 'http://bigscreen.jywj12333.com:90/getPage?channel=bgs'){
		console.log(this.theOptions);
	}
	console.log('1111111111111------------------------'+options.url);
    const instance = axios.create()
	console.log('2222222222222------------------------'+options.url);
    options = Object.assign(this.getInsideConfig(), options)
	console.log('3333333333333------------------------'+options.url);
    this.interceptors(instance, options.url)
	console.log('4444444444444------------------------'+options.url);
	var result = instance(options);
	console.log(options.url);
	console.log(result);
	console.log('5555555555555------------------------'+options.url);
	if (!result){
		return this.request(options);
	}
    return result;
  }
}
export default HttpRequest
